package com.jkdl.springboot.service.impl;

import com.jkdl.springboot.common.util.DateTools;
import com.jkdl.springboot.common.util.JsonResult;
import com.jkdl.springboot.dao.MembershipCardUserMapper;
import com.jkdl.springboot.dao.USecondUsersMapper;
import com.jkdl.springboot.entity.MembershipCardUser;
import com.jkdl.springboot.entity.USecondUsers;
import com.jkdl.springboot.service.MembershipCardUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@Service
public class MembershipCardServiceUserImpl implements MembershipCardUserService {

    @Autowired
    private MembershipCardUserMapper membershipCardUserMapper;

    @Autowired
    private USecondUsersMapper uSecondUsersMapper;

    @Override
    public JsonResult addMembershipCardUser(MembershipCardUser membershipCardUser) {
        if(!membershipCardUser.getValidityPeriod().equalsIgnoreCase("不限")){
            if(membershipCardUser.getUnit().equalsIgnoreCase("年")){
                membershipCardUser.setLastTime(DateTools.getYear(Integer.parseInt(membershipCardUser.getUnit())));
            }else{
                membershipCardUser.setLastTime(DateTools.getMonth(Integer.parseInt(membershipCardUser.getUnit())));
            }
        }
        USecondUsers uSecondUsers = uSecondUsersMapper.selectByPrimaryKey(Integer.parseInt(membershipCardUser.getUserId()));
        membershipCardUser.setStatus(0);
        membershipCardUser.setPaymentStatus(0);
        membershipCardUser.setCreateTime(new Date());
        membershipCardUser.setVersion(0);
        membershipCardUser.setOpenId(uSecondUsers.getOpenid());
        ThreadLocalRandom tlr = ThreadLocalRandom.current();
        Integer random = tlr.nextInt(1000,9999);
        Integer random2 = tlr.nextInt(1000,9999);
        membershipCardUser.setCardNumber(random + " " + random2 +" "+ membershipCardUser.getPhone().substring(membershipCardUser.getPhone().length() -3));

        int insert = membershipCardUserMapper.insert(membershipCardUser);

        if(insert > 0){
            return JsonResult.ok("添加成功");
        }else{
            return JsonResult.build("添加失败");
        }

    }
}
